﻿using CrawlerFramework.CrawlerEngine;
using CrawlerFramework.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace CrawlerFramework.Scheduler
{
    public class Task:ITask
    {
        public Task(ICrawlerEngine crawlerEngine, ScheduledJob job)
        {
            this.CrawlerEngine = crawlerEngine;
            this.Job = job;
        }

        public bool IsRunning { get; private set; }
        
        public System.Threading.Timer Timer { get; private set; }

        public Models.ScheduledJob Job { get; private set; }

        public CrawlerEngine.ICrawlerEngine CrawlerEngine { get; private set; }

        private bool Init()
        {
            var onceTime = Job.IsRunOneTime();
            if (onceTime && Job.LastEnd != null)
                return false;

            var interval = onceTime ? TimeSpan.FromHours(0) : TimeSpan.FromHours(Job.Hours);
            if (this.Timer == null)
                Timer = new Timer(TimerHandler, null, interval, interval);

            return true;
        }

        private void TimerHandler(object context)
        {
            Timer.Change(-1, -1);
            IsRunning = true;
            CrawlerEngine.ExecuteScheduledJob(Job.JobGuid);
            IsRunning = false;
            if (this.Job.IsRunOneTime())
            {
                this.Dispose();
            }
            else
            {
                var interval = TimeSpan.FromHours(Job.Hours);
                Timer.Change(interval, interval);
            }
        }

        private void Dispose()
        {
            if (Timer != null)
            {
                Timer.Dispose();
                Timer = null;
            }
        }

        public void Execute()
        {
            this.Init();
        }
    }
}
